//
//  DefaultProfiler.m
//  SDKUI
//
//  Created by aiquantong on 17/08/2017.
//  Copyright © 2017 aiquantong. All rights reserved.
//

#import "DefaultCustomProfileManager.h"
#import "ProfileManager.h"

@interface DefaultCustomProfileManager()

@property (nonatomic, strong) CustomProfileModel *curUserProfile;

@end


@implementation DefaultCustomProfileManager


-(CustomProfileModel *)getCacheCustomProfileModel;
{
    if (self.curUserProfile) {
        return self.curUserProfile;
    }else{
        [self customCurProfileCallback:^(CustomProfileModel *model) {
            
        }];
    }
    return nil;
}

-(void)customCurProfileCallback:(void (^)(CustomProfileModel *model))callback;
{
    if (!self.curUserProfile) {
        CustomProfileModel *cpm = [[CustomProfileModel alloc] init];
        cpm.nickName = [Kandy sharedInstance].sessionManagement.currentUser.record.userName;
        self.curUserProfile = cpm;
    }

    __weak typeof(self) weekself = self;
    [ProfileManager getCurUserProfile:^(NSError *error, KandyUserProfile *userProfile) {
        typeof(self) strongself = weekself;
        if (!error) {
            KandyUserProfileParams *upp = userProfile.userProfileParams;
            if(upp.displayName){
                strongself.curUserProfile.nickName = upp.displayName;
            }
        }
        callback(strongself.curUserProfile);
    }];
}


-(void)customProfileRetireWithUserId:(NSString *)userId callback:(void (^)(CustomProfileModel *model))callback;
{
    if (callback && userId) {
        [ProfileManager getUserProfileWithUserId:userId callback:^(NSError *error, KandyUserProfile *userProfile) {
            CustomProfileModel *cpm = [[CustomProfileModel alloc] init];
            NSArray *userArr = [userId componentsSeparatedByString:@"@"];
            cpm.nickName = [userArr firstObject];
            
            if (error) {
                callback(cpm);
            }else{
                KandyUserProfileParams *upp = userProfile.userProfileParams;
                if (upp.imageUUID) {
                    [ProfileManager downloadUserProfileImage:userProfile.userProfileParams.imageUUID callback:^(NSError *error, NSString *filePath) {
                        if(upp.displayName){
                            cpm.nickName = upp.displayName;
                        }
                        if (!error) {
                            cpm.headerImg = [[UIImage alloc] initWithContentsOfFile:filePath];
                        }
                        callback(cpm);
                    }];
                }else if(upp.displayName){
                    cpm.nickName = upp.displayName;
                    callback(cpm);
                }else{
                    callback(cpm);
                }
            }
        }];
    }
}

@end




